<template>
  <div class="likes-favorites-container">
    <div class="container py-4">
      <!-- 页面标题 -->
      <div class="row mb-4">
        <div class="col">
          <h2 class="mb-0">我的互动</h2>
          <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
              <li class="breadcrumb-item">
                <a href="#" @click.prevent="$router.push('/user/profile')">个人中心</a>
              </li>
              <li class="breadcrumb-item active" aria-current="page">我的互动</li>
            </ol>
          </nav>
        </div>
      </div>

      <!-- 标签页 -->
      <ul class="nav nav-tabs mb-4">
        <li class="nav-item">
          <a class="nav-link" :class="{ active: activeTab === 'likes' }" @click="activeTab = 'likes'" href="#">
            <!-- 使用导入的 SVG 图标 -->
            <img src="@/assets/images/LikesFavorites/点赞.svg" width="16" height="16" class="me-1" alt="点赞图标" />
            <span :class="{ 'text-primary': activeTab === 'likes', 'text-dark': activeTab !== 'likes' }">点赞</span>
            <span class="badge bg-primary ms-1">{{ likes.length }}</span>
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" :class="{ active: activeTab === 'favorites' }" @click="activeTab = 'favorites'" href="#">
            <!-- 使用导入的 SVG 图标 -->
            <img src="@/assets/images/LikesFavorites/收藏.svg" width="16" height="16" class="me-1" alt="收藏图标" />
            <span :class="{ 'text-primary': activeTab === 'favorites', 'text-dark': activeTab !== 'favorites' }">收藏</span>
            <span class="badge bg-warning text-dark ms-1">{{ favorites.length }}</span>
          </a>
        </li>
      </ul>

      <!-- 错误提示 -->
      <div v-if="error" class="alert alert-danger" role="alert">
        <h4 class="alert-heading">加载失败!</h4>
        <p>{{ error }}</p>
        <hr>
        <button class="btn btn-outline-danger" @click="fetchData">重新加载</button>
      </div>

      <!-- 加载状态 -->
      <div v-else-if="loading" class="d-flex justify-content-center my-5">
        <div class="spinner-border text-primary" role="status">
          <span class="visually-hidden">加载中...</span>
        </div>
        <span class="ms-2">正在加载数据...</span>
      </div>

      <!-- 内容容器 -->
      <div class="content-container" style="height: 600px; overflow-y: auto;">
        <!-- 点赞内容 -->
        <div v-if="activeTab === 'likes'">
          <div v-if="likes.length === 0" class="text-center py-5">
            <div class="text-muted mb-3">
              <i class="bi bi-hand-thumbs-up fs-1"></i>
            </div>
            <h5 class="text-muted">暂无点赞记录</h5>
            <p class="text-muted">快去发现喜欢的内容并点赞吧</p>
            <button class="btn btn-primary" @click="$router.push('/')">去发现</button>
          </div>
          
          <div v-else>
            <div class="row">
              <transition-group name="card" tag="div" class="row">
                <div v-for="like in likes" :key="like.id" class="col-12 mb-4">
                  <div class="card h-100 shadow-sm">
                    <div class="row g-0">
                      <div class="col-md-3 d-flex align-items-center">
                        <img :src="like.postCover || '@/assets/images/default-cover.jpg'" class="img-fluid rounded-start h-100 object-fit-cover" alt="帖子封面" style="height: 150px; width: 100%; object-fit: cover;" @error="handleImageError($event)">
                      </div>
                      <div class="col-md-9">
                        <div class="card-body">
                          <h5 class="card-title">
                            <a href="#" @click.prevent="goToPost(like.postId)" class="text-decoration-none">
                              {{ like.postTitle }}
                            </a>
                          </h5>
                          <div class="d-flex justify-content-between text-muted mb-2">
                            <span>作者: {{ like.postAuthor }}</span>
                            <span class="small">加入时间：{{ formatDate(like.createdAt) }}</span>
                          </div>
                          <div class="d-flex justify-content-between align-items-center mt-3">
                            <button class="btn btn-sm btn-primary" @click="goToPost(like.postId)">
                              <i class="bi bi-file-earmark-text"></i> 详情
                            </button>
                            <button class="btn btn-sm btn-outline-danger" @click="removeLike(like.id)">
                              <i class="bi bi-x-lg"></i> 取消点赞
                            </button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </transition-group>
            </div>
          </div>
        </div>

        <!-- 收藏内容 -->
        <div v-else-if="activeTab === 'favorites'">
          <div v-if="favorites.length === 0" class="text-center py-5">
            <div class="text-muted mb-3">
              <i class="bi bi-star fs-1"></i>
            </div>
            <h5 class="text-muted">暂无收藏记录</h5>
            <p class="text-muted">快去发现喜欢的内容并收藏吧</p>
            <button class="btn btn-primary" @click="$router.push('/')">去发现</button>
          </div>
          
          <div v-else>
            <div class="row">
              <transition-group name="card" tag="div" class="row">
                <div v-for="favorite in favorites" :key="favorite.id" class="col-12 mb-4">
                  <div class="card h-100 shadow-sm">
                    <div class="row g-0">
                      <div class="col-md-3 d-flex align-items-center">
                        <img :src="favorite.postCover || '@/assets/images/default-cover.jpg'" class="img-fluid rounded-start h-100 object-fit-cover" alt="帖子封面" style="height: 150px; width: 100%; object-fit: cover;" @error="handleImageError($event)">
                      </div>
                      <div class="col-md-9">
                        <div class="card-body">
                          <h5 class="card-title">
                            <a href="#" @click.prevent="goToPost(favorite.postId)" class="text-decoration-none">
                              {{ favorite.postTitle }}
                            </a>
                          </h5>
                          <div class="d-flex justify-content-between text-muted mb-2">
                            <span>作者: {{ favorite.postAuthor }}</span>
                            <span class="small">加入时间：{{ formatDate(favorite.createdAt) }}</span>
                          </div>
                          <div class="d-flex justify-content-between align-items-center mt-3">
                            <button class="btn btn-sm btn-warning" @click="goToPost(favorite.postId)">
                              <i class="bi bi-file-earmark-text"></i> 详情
                            </button>
                            <button class="btn btn-sm btn-outline-danger" @click="removeFavorite(favorite.id)">
                              <i class="bi bi-x-lg"></i> 取消收藏
                            </button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </transition-group>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserLikesService, 
          getUserFavoritesService, 
          removeLikeService, 
          removeFavoriteService,
          getAuthorService } from '@/api/LikesFavorites.js'

import { getPostDetailService,
          getPostCoverByIdService } from '@/api/post.js'

import useUserInfoStore from '@/stores/userInfo.js'


const userInfoStore = useUserInfoStore()
const router = useRouter()

// 用户信息
const userInfo = userInfoStore

// 活跃标签页
const activeTab = ref('likes')

// 点赞数据
const likes = ref([])

// 收藏数据
const favorites = ref([])

// 加载状态
const loading = ref(true)

// 错误信息
const error = ref(null)

// 获取用户点赞和收藏记录
const fetchData = async () => {
  try {
    loading.value = true
    error.value = null
    
    // 获取点赞数据
    const likesRes = await getUserLikesService(userInfo.info.id, "like")
    
    // 为每个点赞项获取详细信息
    likes.value = await Promise.all(likesRes.data.map(async (like) => {
      // 获取帖子详情
      const postRes = await getPostDetailService(like.postId)
      const post = postRes.data

      // 获取作者信息
      const authorRes = await getAuthorService(post.userId)
      
      // 获取帖子封面
      let postCover = ''
      try {
        const coverRes = await getPostCoverByIdService(post.id)
        if (coverRes.data && coverRes.data.length > 0) {
          // 如果有多个图片，默认显示第一张
          const firstImage = coverRes.data[0]
          // 添加路径前缀
          postCover = firstImage.imageUrl.startsWith('http') 
            ? firstImage.imageUrl 
            : `http://localhost:8080${firstImage.imageUrl}`
        }
      } catch (error) {
        console.warn('获取封面图片失败:', error)
      }
      
      return {
        ...like,
        postTitle: post.title,
        postAuthor: authorRes.data,
        createdAt: like.createdAt,
        postCover: postCover
      }
    }))
    
    // 获取收藏数据
    const favoritesRes = await getUserFavoritesService(userInfo.info.id, "favorite")
    // 为每个收藏项获取详细信息
    favorites.value = await Promise.all(favoritesRes.data.map(async (favorite) => {
      // 获取帖子详情
      const postRes = await getPostDetailService(favorite.postId)
      const post = postRes.data
      
      // 获取作者信息
      const authorRes = await getAuthorService(post.userId)
      
      // 获取帖子封面
      let postCover = '@/assets/images/封面加载失败.webp'
      try {
        const coverRes = await getPostCoverByIdService(post.id)
        if (coverRes.data && coverRes.data.length > 0) {
          // 如果有多个图片，默认显示第一张
          const firstImage = coverRes.data[0]
          // 添加路径前缀
          postCover = firstImage.imageUrl.startsWith('http') 
            ? firstImage.imageUrl 
            : `http://localhost:8080${firstImage.imageUrl}`
        }
      } catch (error) {
        console.warn('获取封面图片失败:', error)
      }
      
      return {
        ...favorite,
        postTitle: post.title,
        postAuthor: authorRes.data,
        createdAt: favorite.createdAt,
        postCover: postCover
      }
    }))


  } catch (err) {
    console.error('获取数据失败:', err)
    error.value = `获取数据失败: ${err.message || '未知错误'}`
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 跳转到帖子详情
const goToPost = (postId) => {
  router.push(`/post/detail/${postId}`)
}

// 处理图片加载错误
const handleImageError = (event) => {
  event.target.src = new URL('@/assets/images/封面加载失败.webp', import.meta.url).href
}

//取消点赞
const removeLike = (likeId) => {
  ElMessageBox.confirm('确定要取消点赞吗？', '确认操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await removeLikeService(likeId)
      // 从列表中移除
      likes.value = likes.value.filter(like => like.id !== likeId)
      ElMessage.success('已取消点赞')
    } catch (err) {
      console.error('取消点赞失败:', err)
      ElMessage.error('取消点赞失败')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 取消收藏
const removeFavorite = (favoriteId) => {
  ElMessageBox.confirm('确定要取消收藏吗？', '确认操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await removeFavoriteService(favoriteId)
      // 从列表中移除
      favorites.value = favorites.value.filter(favorite => favorite.id !== favoriteId)
      ElMessage.success('已取消收藏')
    } catch (err) {
      console.error('取消收藏失败:', err)
      ElMessage.error('取消收藏失败')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 初始化数据
onMounted(() => {
  fetchData()//获取点赞和收藏数据
})
</script>

<style scoped>
.likes-favorites-container {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding-top: 20px; /* 添加一些顶部内边距 */
}

.nav-tabs .nav-link {
  cursor: pointer;
  border: none;
  background-color: transparent;
  transition: all 0.3s ease;
}

.nav-tabs .nav-link:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.nav-tabs .nav-link.active {
  border-bottom: 2px solid #0d6efd;
  font-weight: 500;
}

.card {
  transition: all 0.3s ease;
  transform: translateY(0);
  opacity: 1;
}

.card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.15);
}

.breadcrumb {
  background-color: transparent;
  padding: 0;
}

.breadcrumb-item a {
  text-decoration: none;
  color: #6c757d;
  transition: color 0.2s ease;
}

.breadcrumb-item a:hover {
  color: #0d6efd;
}

.breadcrumb-item.active {
  color: #495057;
}

/* 淡入淡出过渡效果 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

/* 滑动淡出过渡效果 */
.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter-from {
  transform: translateX(20px);
  opacity: 0;
}

.slide-fade-leave-to {
  transform: translateX(-20px);
  opacity: 0;
}

/* 卡片入场动画 */
.card-enter-active {
  transition: all 0.5s ease;
}

.card-enter-from {
  opacity: 0;
  transform: translateY(30px);
}

.card-enter-to {
  opacity: 1;
  transform: translateY(0);
}

/* 标签页过渡效果 */
.tab-content > .tab-pane {
  display: block;
}

.tab-content > .tab-pane:not(.active) {
  display: none;
}

/* 加载动画 */
.spinner-border {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 内容容器滚动条样式 */
.content-container::-webkit-scrollbar {
  width: 8px;
}

.content-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.content-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.content-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>